package com.central.modules.security.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.constant.Constant;
import com.central.modules.security.dao.SysUserTokenDao;
import com.central.modules.security.entity.SysUserTokenEntity;
import com.central.modules.security.oauth2.TokenGenerator;
import com.central.modules.security.service.SysUserTokenService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
    /**
     * 过期间隔
     */
    private final static int EXPIRE = 24 * 30;

    @Override
    public SysUserTokenEntity getByToken(String token) {
        QueryWrapper<SysUserTokenEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserTokenEntity::getToken, token);
        return this.getOne(queryWrapper);
    }

    @Override
    public SysUserTokenEntity getByUserId(Long userId) {
        QueryWrapper<SysUserTokenEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserTokenEntity::getUserId, userId);
        return this.getOne(queryWrapper);
    }

    @Override
    public void updateToken(Long userId, String token) {
        UpdateWrapper<SysUserTokenEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SysUserTokenEntity::getUserId, userId).set(SysUserTokenEntity::getToken, token);
        this.update(updateWrapper);

    }

    @Override
    public Map<String, Object> createToken(Long userId) {
        //用户token
        String token;

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = DateUtil.offset(now, DateField.HOUR, EXPIRE);

        //判断是否生成过token
        SysUserTokenEntity tokenEntity = this.getByUserId(userId);
        if (tokenEntity == null) {
            //生成一个token
            token = TokenGenerator.generateValue();

            tokenEntity = new SysUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);

            //保存token
            this.save(tokenEntity);
        } else {
            //判断token是否过期
            if (tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
                //token过期，重新生成token
                token = TokenGenerator.generateValue();
            } else {
                token = tokenEntity.getToken();
            }

            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);

            //更新token
            this.updateById(tokenEntity);
        }

        Map<String, Object> map = new HashMap<>(2);
        map.put(Constant.TOKEN_HEADER, token);
        map.put("expire", DateUtil.formatDate(expireTime));
        return map;
    }

    @Override
    public void logout(Long userId) {
        QueryWrapper<SysUserTokenEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserTokenEntity::getUserId, userId);
        this.remove(queryWrapper);

    }
}